import log4js from 'log4js';
const path = require('path');
function getFileAndLine() {
    const orig = Error.prepareStackTrace;
    Error.prepareStackTrace = (_, stack) => stack;
    const err = new Error();
    // Error.captureStackTrace(err, arguments.callee); //这一行在strict的时候会报错。
    Error.prepareStackTrace = orig;

    var str: any = err.stack;// 获取调用栈
    /*
    console.log(str);
    第0层：Error
    第1层：at getFileAndLine (C:\Users\hxw\Desktop\WebTesting\WebServer\src\logger.js:10:17)
    第2层：at Function.info (C:\Users\hxw\Desktop\WebTesting\WebServer\src\logger.js:44:18)
    第3层：at Object.<anonymous> (C:\Users\hxw\Desktop\WebTesting\WebServer\main.js:10:8) //实际输出日志的地方。
    第4层：at Module._compile (internal/modules/cjs/loader.js:778:30)
    */
    str = str.split('\n')[3];
    str = str.split(path.sep);
    var funcName = str[0].split(' ');
    funcName = funcName[funcName.length - 2];

    str = str[str.length - 1];
    str = str.split(':');
    return `[${str[0]}:${str[1]}:${funcName}]`;
}


let programName = 'WebServer'
log4js.configure({
    appenders: {
        console: {
            type: 'console'
        },
        myDateFile: {
            type: 'dateFile',
            filename: `./log/${programName}`,
            pattern: "yyyy-MM-dd.log",
            alwaysIncludePattern: true
        },
    },
    categories: {
        default: {
            appenders: ['console', 'myDateFile'],
            level: 'all'
        }
    }
});
let log: any = log4js.getLogger('default');
class logger {
    static info(message: any, ...args: any[]) {
        log.info(getFileAndLine(), ...arguments);
    }
    static warn(message: any, ...args: any[]) {
        log.warn(getFileAndLine(), ...arguments);
    }
    static error(message: any, ...args: any[]) {
        log.error(getFileAndLine(), ...arguments);
    }
}

export = logger;

// export = log4js.getLogger('default');